
package ling.archives.controller;

import com.easy.query.core.enums.SQLExecuteStrategyEnum;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.*;
import ling.archives.domain.Archive;
import ling.archives.domain.dto.ArchiveContentDto;
import ling.archives.domain.proxy.ArchiveContentProxy;
import ling.archives.service.ArchiveService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.util.AntPathMatcher;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

import lombok.*;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import ling.archives.domain.ArchiveContent;
//import ling.archives.service.ArchiveContentService;
import ling.archives.common.*;
import ling.archives.common.domain.*;
import org.springframework.web.servlet.HandlerMapping;

/** 卷宗内容 控制层
 * @author : He-LiangLiang@Outlook.com
 * @date : 2025-3-26
 */
@Api(tags = "卷宗内容 功能接口")
@RestController
@RequestMapping("/archives/ArchiveContent")
public class ArchiveContentController extends EQueryController<ArchiveContent>{


    @javax.annotation.Resource
    ArchiveService archiveService;
    @ApiOperation("详情")
    @PreAuthorize("@ar.any(@ar.archiveContent.query)")
    @GetMapping(value = "/{id}")
    public Result<ArchiveContent> getInfo(@PathVariable("id") Long id)
    {
       var entity= queryHelper.entityQuery(ArchiveContent.class).include(a -> a.archive())
                .whereById(id).firstOrNull();
        return Result.ok(entity);
    }


    @ApiOperation(value = "分页列表",notes = "添加分类标题：archive.doccId_title")
    @PreAuthorize("@ar.any(@ar.archiveContent.list)")
    @GetMapping("list")
    public ResultRows<ArchiveContent> list(ArchiveContentDto dto, PageSort pageRequest) {

        //按所属乡镇管理数据
        List<String> towns=new ArrayList<String>();
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId()))
            towns=null;
        else {
            var roleKsys = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(p -> p.getRoleKey()).collect(Collectors.toList());
            var perfixStr = "ar_town_";
            var roleTowns = roleKsys.stream().filter(p -> p.length() > perfixStr.length() && p.startsWith(perfixStr))
                    .map(p -> p.replace(perfixStr, "")).collect(Collectors.toList());
            towns = roleTowns;
            if (roleTowns.stream().anyMatch(p -> Objects.equals(p, "*"))) {
                towns = null;
            }
        }
        if(towns!=null&& towns.isEmpty())
            return ResultRows.toEmpty("无乡镇查看权限");
        var quSql = queryHelper.entityQuery(Archive.class).whereObject(dto.getArchive() != null, dto.getArchive());

        List<String> finalTowns = towns;
        var psges = queryHelper.entityQuery(ArchiveContent.class).include(a -> a.archive())
                .where(finalTowns!=null,a -> a.townName().in(finalTowns))
                .where(quSql.getSQLEntityExpressionBuilder().hasWhere(), a -> a.archive().id().in(quSql.selectColumn(p -> p.id())))
                .whereObject(dto).orderByObject(pageRequest).toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
        var ds = archiveService.DoccTypeList();

        psges.getData().forEach(p ->
                ds.stream().filter(x -> Objects.equals(x.getId(), p.getArchive().getDoccId()))
                        .findFirst().ifPresent(z -> p.getArchive().ExtendMapSet("doccId_title", z.getTitle())));
        return toResultRows(psges);
    }
    @ApiOperation("新增")
    @PreAuthorize("@ar.any(@ar.archiveContent.add)")
    @Log(title = "卷宗内容", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public Result add(@Validated @RequestBody ArchiveContent entity){
        return super.add(entity);
    }
    @ApiOperation("删除")
    @PreAuthorize("@ar.any(@ar.archiveContent.remove)")
    @Log(title = "卷宗内容", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable("ids") Integer[] ids){
        return super.remove(Arrays.stream(ids).toArray());
    }
    @ApiOperation("编辑")
    @PreAuthorize("@ar.any(@ar.archiveContent.edit)")
    @Log(title = "卷宗内容", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public  Result edit(@Validated @RequestBody ArchiveContent entity){
        entity.setTitle(entity.gainTitle());
        return super.edit(entity);
    }
    @ApiOperation("更新数据-根据非空值")
    @PreAuthorize("@ar.any(@ar.archiveContent.edit)")
    @Log(title = "卷宗内容", businessType = BusinessType.UPDATE)
    @PostMapping("editByNameValue")
    public  Result editByNameValue(@RequestBody ArchiveContent entity){

        var re=queryHelper.entityQuery().updatable(entity).setSQLStrategy(SQLExecuteStrategyEnum.ONLY_NOT_NULL_COLUMNS).executeRows();
        var item=queryHelper.entityQuery(ArchiveContent.class).whereById(entity.getId()).firstOrNull();
        if(!Objects.equals(item.gainTitle(), item.getTitle()))
        {
            item.setTitle(item.gainTitle());
            queryHelper.entityQuery().updatable(item).setColumns(ArchiveContentProxy::title).executeRows();
        }
        return Result.restResult(re>0,null,null);
    }
    @ApiOperation(value = "户主姓名修改",notes = "对象中只需要：id,householdHead")
    @PreAuthorize("@ar.any(@ar.archiveContent.edit)")
    @Log(title = "卷宗内容", businessType = BusinessType.UPDATE)
    @PostMapping("editHouseholdHead")
    public  Result editHouseholdHead(@RequestBody ArchiveContent entity) {
        if (StringUtils.isBlank(entity.getHouseholdHead()))
            return Result.bad("名称格式错误");
        var old = queryHelper.entityQuery(ArchiveContent.class).whereById(entity.getId()).firstOrNull();
        old.setHouseholdHead(entity.getHouseholdHead());
        old.setTitle(old.gainTitle());
        var py=archiveService.gainHeadComb(old.getHouseholdHead());
        old.setHeadPy(py);
        var re = queryHelper.entityQuery().updatable(old).executeRows();
        return Result.restResult(re > 0, null, null);
    }

    @ApiOperation("作废")
    @PreAuthorize("@ar.any(@ar.archiveContent.edit)")
    @Log(title = "卷宗内容", businessType = BusinessType.UPDATE)
    @PostMapping("toCancel")
    public  Result toCancel(@RequestBody ArchiveContent entity){
        if(!Objects.equals(entity.getStatus(), "2"))
            return Result.bad("状态错误");
       var old= queryHelper.entityQuery(ArchiveContent.class).whereById(entity.getId()).firstOrNull();
       if(!Objects.equals(old.getStatus(), "0"))
           return Result.bad("数据状态错误");
        old.setStatus("2");
        return super.edit(old);
    }

    @ApiOperation("导出")
    @PreAuthorize("@ar.any(@ar.archiveContent.export)")
    @Log(title = "卷宗内容", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ArchiveContent entity, PageDomain pageRequest,HttpServletResponse response)
    {
        super.export(entity,pageRequest,null,response);
    }


    @ApiOperation("资源文件访问")
    @GetMapping("/file/**")
    public ResponseEntity<Resource> downloadFile(HttpServletRequest request) throws IOException {
        String filePath=antUrl(request);
        // 验证文件路径是否为空
        if (filePath == null || filePath.trim().isEmpty()) {
            throw new IllegalArgumentException("文件路径不能为空");
        }
        var basePath=ArchiveService.ContentFileBasePath;
        var fullPath=basePath+filePath;
        // 将路径转换为Path对象
        Path path = Paths.get(fullPath);
        File file = path.toFile();

        // 验证文件是否存在
        if (!file.exists()||!file.isFile()) {
            return ResponseEntity.status(404).build();
        }
        // 创建资源对象
        Resource resource = new FileSystemResource(fullPath);
        // 获取文件MIME类型
        String contentType = Files.probeContentType(path);
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, contentType);
        // 返回文件响应
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .body(resource);
    }
    String antUrl(HttpServletRequest request) {
        String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); // 如 "/files/**"
        String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); // 如 "/files/images/cat.jpg"

        // 使用 AntPathMatcher 提取通配符匹配的剩余路径
        AntPathMatcher pathMatcher = new AntPathMatcher();
        return pathMatcher.extractPathWithinPattern(pattern, fullPath);
    }

}